import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/utils/Device.dart';

class CAppBar extends StatefulWidget implements PreferredSizeWidget {

  final Color bgColor;
  final String title;
  final Color titleColor;
  final TitlePosition titlePosition;
  final String backImgUrl;
  final void Function()? onBack;
  final List<Widget> actions;
  final void Function(int)? onPressed;
  final bool showBack;
  final SystemUiOverlayStyle? overlayStyle;

  const CAppBar({Key? key,
    this.bgColor = Colors.transparent,
    this.title = '',
    this.titleColor = Colors.black,
    this.titlePosition = TitlePosition.androidLeftIosCenter,
    this.backImgUrl = '',
    this.onBack,
    this.actions = const [], 
    this.onPressed, 
    this.showBack = true,
    this.overlayStyle,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CAppBarState();
  }

  @override
  Size get preferredSize => Size.fromHeight(48);
}

class _CAppBarState extends BaseState<CAppBar> {

  late String _backImgUrl;
  late SystemUiOverlayStyle? _overlayStyle;

  @override
  Widget build(BuildContext context) {

    _backImgUrl = widget.backImgUrl;
    _overlayStyle = widget.overlayStyle;

    if (_overlayStyle == null) {
      _overlayStyle = ThemeData.estimateBrightnessForColor(widget.bgColor) == Brightness.dark
          ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark;
    }
    if (_backImgUrl.isEmpty) {
      if (_overlayStyle == SystemUiOverlayStyle.light) {
        _backImgUrl = 'ic_white_arrow';
      } else {
        _backImgUrl = 'ic_black_arrow';
      }
    }

    return AnnotatedRegion<SystemUiOverlayStyle>(
        value: _overlayStyle!,
        child: Material(color: widget.bgColor,
          child: SafeArea(
            bottom: false,
            child: Container(height: 48,
              child: Stack(alignment: Alignment.centerLeft, children: <Widget>[
                buildBack(),
                buildTitle(),
                buildActions(),
              ]),
            ),
          )
        )
    );
  }

  Widget buildBack() {
    return widget.showBack ? IconButton(
      onPressed: () async {
        if (widget.onBack != null) {
          widget.onBack!();
        } else {
          FocusManager.instance.primaryFocus?.unfocus();
          final isBack = await Navigator.maybePop(context);
          if (!isBack) {
            await SystemNavigator.pop();
          }
        }
      },
      tooltip: 'Back',
      padding: const EdgeInsets.all(12.0),
      icon: LoadImage(
        _backImgUrl,
        // color: backImgColor ?? ThemeUtils.getIconColor(context),
      ),
    ) : W(0);
  }

  Widget buildTitle() {
    AlignmentGeometry align = Alignment.center;
    if (widget.titlePosition == TitlePosition.left) {
      align = Alignment.centerLeft;
    } else if (widget.titlePosition == TitlePosition.androidLeftIosCenter) {
      if (Device.isAndroid) {
        align = Alignment.centerLeft;
      }
    }
    return Container(
      alignment: align,
      width: double.infinity,
      child: Text(
        widget.title,
        style: TS(17, widget.titleColor),
      ),
      margin: const EdgeInsets.symmetric(horizontal: 48.0),
    );
  }
  
  Widget buildActions() {
    List<Widget> actions = [];
    widget.actions.forEach((element) {
      actions.add(element);
      actions.add(W(16));
    });
    return Positioned(
      child: Row(
        mainAxisSize: MainAxisSize.min, 
        mainAxisAlignment: MainAxisAlignment.end,
        children: [...actions],
      ),
      right: 0,
    );
  }
}

enum TitlePosition {
  left, center, androidLeftIosCenter
}